#include "btree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int btree_insert(NODE** root, DATA data)
{
	NODE *pnew = (NODE*)malloc(sizeof(NODE));
	if(!pnew)
	{
		puts("插入失败");
		return -1;
	}
	pnew -> data = data;
	pnew -> left = NULL;
	pnew -> right = NULL;
	if(*root == NULL)
	{
		*root = pnew;
		return 0;
	}
	NODE* p = *root;
	NODE* q = NULL;
	while(p)
	{
		q = p;
		if(memcmp(&(p -> data),&data,sizeof(DATA)) < 0)
			p = p -> right;
		else
			p = p -> left;
	}
	if(memcmp(&(q -> data),&data,sizeof(DATA)) < 0)
		q -> right = pnew;
	else
		q -> left = pnew;
	return 0;
}
	
void btree_first(const NODE* root)
{
	if(!root)
		return ;
	printf("%d\t",root -> data);
	btree_first(root -> left);
	btree_first(root -> right);
}

void btree_mid(const NODE* root)
{
	if(!root)
		return ;
	btree_mid(root -> left);
	printf("%d\t",root -> data);
	btree_mid(root -> right);
}

void btree_later(const NODE* root)
{
	if(!root)
		return ;
	btree_later(root -> left);
	btree_later(root -> right);
	printf("%d\t",root -> data);
}

static void btree_destory(NODE *root)
{
	if(!root)
		return ;
	btree_destory(root -> left);
	btree_destory(root -> right);
	free(root);
}

int btree_free(NODE **root)
{
	btree_destory(*root);
	*root = NULL;
	return 0;
}
